package com.h5;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cyz.service.UserCouponService;
import com.demo.annotation.LoginFilter;
import com.demo.util.DateUtil;
import com.demo.util.JSONUtils;
import com.shopcart.domain.Order;
import com.shopcart.domain.OrderDetail;
import com.shopcart.domain.Store;
import com.shopcart.domain.StoreGoods;
import com.shopcart.service.OrderService;
import com.shopcart.service.QuickShoppingService;
import com.vsd.domain.UserCoupon;
import com.vsd.mobile.error.MEnumError;
import com.vsd.service.CodeService;
import com.vsd.service.StoreGoodsService;
import com.vsd.service.StoreService;
import com.zy.order.proto.MSOrder.MCoupon;

@Controller
@RequestMapping("/m/order")
public class H5OrderController extends H5BaseController{

	@Autowired
	StoreGoodsService storeGoodsService;
	@Autowired
	StoreService storeService;
	@Autowired
	UserCouponService userCouponService;
	@Autowired
	CodeService codeService;
	@Autowired
	OrderService orderService;
	@Autowired
	QuickShoppingService quickShoppingService;
	
	@RequestMapping("{id}")
	public String detai(@PathVariable("id")String id,ModelMap map){
		map.put("id", id);
		return BASE_PATH+"/orderDetail";
	}
	
	@RequestMapping("/list")
	@ResponseBody
	@LoginFilter(outpage="/m/login")
	public String orderList(HttpSession session,Integer page,Integer limit,Integer state){
		String userId = getSessionParameter(session, "id");
		return orderService.selectMyOrders(userId, page, limit,state);
	}
	
	@RequestMapping("/update")
	@ResponseBody
	public String updateOrder(String id,Integer type,String info){
		Order order = orderService.findById(id);
		if(order==null) return JSONUtils.serialize(new Ret(MEnumError.ORDER_NOT_FOUND));
		Integer state = order.getState() == null ? 0 : order.getState();
		switch (type) {
		case 1 :
			/**********************************修改***取消订单**************************************************/
			if ((order.getPayType() == 1 && state != 1)||(order.getPayType() == 2 && state != 2)) {
				return JSONUtils.serialize(new Ret(MEnumError.ORDER_HASPAY_ERROR));
			}
			/**********************************修改***取消订单**************************************************/
			 
			// 退回优惠券
			String couponId = order.getStoreCoupon();
			if (StringUtils.isNotBlank(couponId)) {
				UserCoupon coupon = new UserCoupon();
				coupon.setId(couponId);
				coupon.setState(1);
				userCouponService.update(coupon);
			}

			order.setState(-1); // 取消订单
			order.setBackTime(new Date());
		/**********11271335*******************************/
			order.setBackReason(info);
		/************************************************/
			break;
		case 2 :
			order.setBackState(6); // 退款
			order.setBackTime(new Date());
		/*********11271335********************************/
			order.setBackReason(info);
		/************************************************/
			break;
		case 3 :
			// 删除已取消或已完成的订单
			if (order.getBackState() != 7){
				if (state == 1 || state == 3 || state == 2) {
					return JSONUtils.serialize(new Ret(MEnumError.ORDER_DELETE_ERROR));
				}
			}
			order.setIsShow(0);
			break;
		case 4 :
			if (state == 3){
				order.setState(4); // 交易完成
			}
			break;
		default :
			return JSONUtils.serialize(new Ret(MEnumError.PARAM_WRONG_ERROR));
	}
	order.setModifyTime(new Date());
	
	orderService.updateByPrimaryKey(order);
	return JSONUtils.serialize(new Ret(1));
	}
	
	@RequestMapping("/detail")
	@ResponseBody
	public String detail(String id){
		Order o = orderService.findById(id);
		if(o==null) return JSONUtils.serialize(new Ret(MEnumError.ORDER_NOT_FOUND));
		
		//查找orderDetail
		Collection<OrderDetail> list = orderService.selectDetails(id);
		int totalNum = 0 ;
		JSONObject ret = new JSONObject();
		JSONArray carts = new JSONArray();
		for (OrderDetail d : list) {
			JSONObject c = new JSONObject();
			c.put("name", d.getGoodsName());
			c.put("num", d.getNum());
			c.put("type", d.getGoodsType());
			c.put("img", d.getGoodsImg());
			totalNum+=d.getNum();
			carts.add(c);
		}
		ret.put("carts", carts);
		ret.put("code", o.getCode());
		ret.put("id", o.getId());
		ret.put("img", carts.getJSONObject(0).get("img"));
		ret.put("info", o.getInfo());
		ret.put("payType", o.getPayType());
		ret.put("state", o.getState());
		ret.put("storeId", o.getStoreId());
		ret.put("storeName", o.getStoreName());
		ret.put("time",DateUtil.dateAsQQ(o.getCreateTime()));
		ret.put("total", totalNum);
		ret.put("type", o.getType());
		ret.put("totalPay", o.getTotalPay().toString());
		ret.put("hasComment", o.getHasComment());
		ret.put("storeImg", o.getStoreImg());
		if(o.getCashCoupon()!=null) {
			ret.put("coupon", o.getCashCoupon().toString());
		}
		if(o.getWineMoney()!=null) {
			ret.put("wine", o.getWineMoney().toString());
		}
		return JSONUtils.serialize(ret);
	}
	
	@RequestMapping("/comment/{id}")
	public String toComment(@PathVariable("id")String id,ModelMap map){
		map.put("id", id);
		return BASE_PATH+"/comment";
	}
	
	@RequestMapping("/diancan")
	@ResponseBody
	public String diancan(HttpSession session,String storeId,String data){
		String userId = getSessionParameter(session, "id");
		userId = "1";
		JSONArray array = JSONArray.parseArray(data);
		JSONObject ret = new JSONObject();
		ret.put("code", 0);
		JSONObject youhui = new JSONObject();
		BigDecimal total = BigDecimal.ZERO;
		BigDecimal totalWine = BigDecimal.ZERO;
		BigDecimal winNeed = BigDecimal.ZERO;//需支付酒水
		JSONArray goods = new JSONArray();
		JSONArray wine = new JSONArray();
		for (int i = 0;i<array.size();i++){
			JSONObject cart = array.getJSONObject(i);
			StoreGoods g = storeGoodsService.findById(cart.getString("id"));
			if (g == null){
				return JSONUtils.serialize(new Ret(MEnumError.ORDER_GOODS_NOT_EXIST));
			}
			cart.put("img", g.getImg());
			cart.put("name", g.getName());
			cart.put("price", g.getNowPrice());
			if(StringUtils.isBlank(storeId)&&g.getType()!=2){
				storeId = g.getStoreId();
			}
			if(g.getType()==3){
				totalWine = totalWine.add(g.getNowPrice().multiply(new BigDecimal(cart.getIntValue("num"))));
				wine.add(cart);
			}else{
				total = total.add(g.getNowPrice().multiply(new BigDecimal(cart.getIntValue("num"))));
				goods.add(cart);
			}
		}
		ret.put("goods", goods);
		ret.put("wine", wine);
		ret.put("goodsTotal", total.toString());
		ret.put("wineTotal", totalWine.toString());
		Store store = storeService.findById(storeId);
		Integer wineRate = store.getWineRate();
		if(store.getWineRate()==null){
			wineRate = new Integer(codeService.getWineRate());
		}
		
		//可减免酒水
		BigDecimal wineDis = BigDecimal.ZERO;
		if(store.getWineBegin()==null){
			store.setWineBegin(0);
		}
		if(total.floatValue()>store.getWineBegin()){
			wineDis = total.multiply(new BigDecimal(wineRate)).divide(BigDecimal.valueOf(1000),0);
		}
		
		//酒水全部减免
		if(totalWine.compareTo(wineDis)<0){
			wineDis = totalWine;
		}else{
			winNeed = totalWine.subtract(wineDis);
		}
		youhui.put("winNeed", winNeed.toString());
		youhui.put("full", "满"+store.getWineBegin()+"元，送"+store.getWineBegin()*wineRate/1000+"元酒水");
		youhui.put("discount", wineDis.toString());
		youhui.put("total", total.add(winNeed).toString());
		
		ret.put("youhui", youhui);
		
		MCoupon.Builder coupon = userCouponService.getBestCoupont(userId, storeId, total.add(winNeed),null);
		if(coupon!=null){
			JSONObject coup = new JSONObject();
			coup.put("id", coupon.getId());
			coup.put("code", coupon.getCode());
			coup.put("beginTime", coupon.getBeginTime());
			coup.put("endTime", coupon.getEndTime());
			coup.put("value", coupon.getValue());
			
			ret.put("coupon", coup);
		}
		
		
		return JSONUtils.serialize(ret);
	}
	
	@RequestMapping("/addDiancanOrder")
	@ResponseBody
	public String addDiancan(HttpSession session,String storeId,String remark,Integer payType,String data,String couponId){
		String userId = getSessionParameter(session, "id");
		Ret ret=null;
		try {
			ret = orderService.addDiancanOrder(userId, payType, remark, data, couponId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			return JSONUtils.serialize(new Ret(-1,"订单生产失败"));
		}
		return JSONUtils.serialize(ret);
	}
}
